<template>
    <div id="add-edit-model">
        <el-dialog :title="titleCon" v-model="isUseDialog" draggable :close-on-click-modal="false" width="769px"
            :before-close="handleClose" :destroy-on-close="true" @close="clean">
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="120px" :rules="rules">
                <el-row :gutter="35">
                    <template v-if="isBase">
                        <el-col :xs="24" :sm="12" :md="12" :lg="12"
                            :xl="12" class="mb20">
                            <el-form-item label="风险分区">
                                <el-select v-model="riskAreaId" filterable class="m-2" placeholder="选择风险分区"
                                    @change="riskAreaChange">
                                    <el-option v-for="item in riskAreaList" :key="item.id" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                      <template v-if="riskAreaId">
                        <el-col v-if="uploadType === 'scl' || uploadType === 'jha'" :xs="24" :sm="12" :md="12" :lg="12"
                            :xl="12" class="mb20">
                            <el-form-item label="风险分析单元" prop="l_AnalysisUnitId">
                                <el-select v-model="ruleForm.l_AnalysisUnitId" filterable class="m-2"
                                    placeholder="选择分析单元" value-key="id" popper-class="set-select"
                                    :popper-append-to-body="false">
                                    <el-option v-for="item in unitOptions" :key="item.id" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                      </template>
                        <el-col v-if="uploadType === 'tk'" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="培训计划" prop="l_TrainingPlanId">
                                <el-select v-model="ruleForm.l_TrainingPlanId" filterable class="m-2"
                                    placeholder="选择培训计划" value-key="id" popper-class="set-select"
                                    :popper-append-to-body="false">
                                    <el-option v-for="item in unitOptions" :key="item.id" :label="item.v_CourseName"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <el-divider content-position="left">批量上传数据</el-divider>
                    <div style="padding: 0 20px;width: 100%;">
                        <FileView ref="fileRef" isAccept=".xlsx" :fileInfo="fileInfo" :isNeedRequest="false"
                            :componentKey="isAlter" :isMultiple='false' />
                    </div>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis"
                    @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, toRef, toRefs, toRaw, onMounted, watch } from 'vue';
import { FormInstance, FormRules, ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElOption, ElRow, ElSelect, ElMessage } from 'element-plus';
import { sysFileInfoYitId, sysFileInfoMultipleUpload } from '/@/api/centerControl/pubilc';
import FileView from '../file-view.vue';
import {
    SMSDCAnalysisUnitList,
    EduTrainingPlanList,
    SMSDCRiskPartitionList,
} from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    l_AnalysisUnitId: any, // 风险分析单元
    l_TrainingPlanId: any, // 培训计划
}
export default defineComponent({
    name: 'add-edit-model',
    components: { FileView },
    props: {
        isUseDialog: {
            type: Boolean,
            default: false,
        },
        uploadType: {
            type: String,
            default: '',
        },
        neddUrl: {
            type: Function,
            default: () => { }
        },
        isBase: {
            type: Boolean,
            default: false,
        },
        commonInfo: {
            type: Array,
            default: () => [],
        },
    },
    setup(props, ctx) {
        const titleCon = ref();
        const ruleFormRef = ref();
        const unitOptions = ref();
        let sourceId: any;
        const fileInfo = ref();
        const fileRef: any = ref(null);


        const riskAreaId = ref()
        const riskAreaList = ref([])
        const riskAreaChange = async (id: number) => {
            unitOptions.value = []
            state.ruleForm.l_AnalysisUnitId = ''
            const res = await SMSDCAnalysisUnitList({ l_RiskPartitionId: id })
            unitOptions.value = res.data.map((item: any) => {
                return {
                    value: item.id,
                    label: item.v_Name
                }
            })
        }

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive<formType>({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive<FormRules>({
            /*** 放置验证 */
            // 风险分析单元
            l_AnalysisUnitId: [
                { required: true, message: '请选择风险分析单元', trigger: 'change' },
            ],
            l_TrainingPlanId: [
                { required: true, message: '请选择培训计划', trigger: 'change' },
            ],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            riskAreaId.value = ''
            ctx.emit('cancelMassClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!riskAreaId.value) return ElMessage.error('请选择风险分区')
            if (!formEl) return
            formEl.validate(async (valid) => {
                if (valid) {
                    state.repeatDis = true;
                    let param = toRaw(state.ruleForm);
                    uploadFile(param);
                } else {
                    console.log('error submit!')
                    return false
                }
            })
        }

        /*** 上传文件 */
        const uploadFile = async (val: any) => {
            if (fileRef.value && fileRef.value.fileList.length !== 0) {
                if (fileRef.value.fileList.length > 1) {
                    ElMessage({
                        type: 'warning',
                        message: '只能上传一个Excel文件',
                    });
                    return
                } else {
                    let setArr: any = [];
                    let param: any = {};
                    let neddUrl = props.neddUrl;
                    fileRef.value.fileList.map((i: any) => { setArr.push(i.raw) });
                    param.file = setArr;
                    if (props.isBase) {
                        if (props.uploadType === 'scl' || props.uploadType === 'jha') param.l_AnalysisUnitId = state.ruleForm.l_AnalysisUnitId;
                        if (props.uploadType === 'tk') param.l_TrainingPlanId = state.ruleForm.l_TrainingPlanId;
                    }
                    try {
                        let res: any = await neddUrl(param);
                        if (res.success) {
                            ctx.emit('controlMassClick')
                            ctx.emit('updateData');
                            state.repeatDis = false;
                        } else {
                            state.repeatDis = false;
                            ctx.emit('controlMassClick')
                        }
                    } catch (error) { state.repeatDis = false; }

                }
            } else {
                ElMessage({
                    type: 'warning',
                    message: '请选择需要上传的Excel文件',
                });
            }
        }

        /*** clean 清空数据 */
        const clean = () => {
            if (ruleFormRef.value) ruleFormRef.value.resetFields();
        }

        /*** 获取数据 */
        // const getInfoFun = async () => {
        //     if (props.isBase) {
        //         if (props.uploadType === 'jha' || props.uploadType === 'scl') {
        //             //  riskAreaId.value = props.commonInfo[0].id
        //             riskAreaList.value = []
        //             const res = await SMSDCRiskPartitionList({})
        //             riskAreaList.value = res.data.map((item: any) => {
        //                 return {
        //                     label: item.v_Name,
        //                     value: item.id,
        //                 }
        //             })
        //         } else {
        //             if (props.commonInfo && props.commonInfo.length !== 0) {
        //                 unitOptions.value = props.commonInfo;
        //             } else {
        //                 let res: any;
        //                 if (props.uploadType === 'jha' || props.uploadType === 'scl') res = await SMSDCAnalysisUnitList({});
        //                 if (props.uploadType === 'tk') res = await EduTrainingPlanList({});
        //                 if (res.success) unitOptions.value = res.data;
        //                 console.log(res, 'res12')
        //             }
        //         }
        //     }
        // }

        /*** 获取雪花id */
        const getXhFun = async () => {
            let res: any = await sysFileInfoYitId({});
            if (res.success) fileInfo.value = JSON.stringify({ sourceId: res.data });
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog, 
        async (newVal) => {
            if (newVal) {
                riskAreaList.value = []
                    const res = await SMSDCRiskPartitionList({})
                    riskAreaList.value = res.data.map((item: any) => {
                        return {
                            label: item.v_Name,
                            value: item.id,
                        }
                    })
                // getXhFun();
                titleCon.value = '批量上传';
                state.repeatDis = false;
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            unitOptions,
            isAlter: 1,
            fileInfo,
            fileRef,
            riskAreaList, riskAreaId, riskAreaChange
        }
    },
})
</script>
<style scoped lang="scss"></style>